package com.sen.controller;

import com.sen.mapper.DepartmentMapper;
import com.sen.mapper.EmployeeMapper;
import com.sen.pojo.Department;
import com.sen.pojo.Employee;
import com.sen.service.DepartmentService;
import com.sen.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;
    @Autowired
    DepartmentService departmentService;

    //查询所有员工
    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeService.getAll();
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    //去添加员工页面
    @GetMapping("/emp")
    public String toAddapge(Model model){
        //查出所有部门
        Collection<Department> departments = departmentService.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/add";
    }

    //添加一个员工成功
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        //调用底层业务方法保存员工信息
        employeeService.save(employee);
        return "redirect:/emps";
    }

    //去员工修改页面
    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id") Integer id, Model model){
        //查出原来数据
        Employee employee = employeeService.getEmployeeById(id);
        Collection<Department> departments = departmentService.getDepartments();
        model.addAttribute("departments",departments);
        model.addAttribute("emp",employee);
        return "emp/update";
    }

    //修改成功
    @PostMapping("/updateEmp")
    public String UpdateEmp(Employee employee){

        employeeService.updateEmployeeById(employee);
        return "redirect:/emps";
    }

    //删除员工
    @GetMapping("/delemp/{id}")
    public String deletEmp(@PathVariable("id") Integer id){
        //调用底层业务方法保存员工信息
        employeeService.deleteEmployeeById(id);
        return "redirect:/emps";
    }

    //退出
    @GetMapping("/user/logout")
    public String userLogout(HttpSession session){
        session.invalidate();
        return "redirect:/index.html";
    }
}
